package com.fastgeek.platform.utils;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 实例化对象工具类
 * 
 * @Title ClassUtils.java
 * @author zhangliang
 * @Description:
 * @version $Rev$
 * @LastModify: $Id$
 */
public class ClassUtil {

	public static Object createObject(String className) throws ClassNotFoundException {
		return createObject(className, null);
	}

	public static Object createObject(Class className) {
		return createObject(className, null);
	}

	public static Object createObject(String className, Object... param) throws ClassNotFoundException {
		return createObject(createClass(className), param);
	}

	public static Object createObject(Class className, Object... param) {
		try {
			if (className != null) {
				if (param != null && param.length > 0) {
					for (Constructor constructors : className.getConstructors()) {
						if (constructors.getParameterTypes().length == param.length) {
							return constructors.newInstance(param);
						}
					}
				}
				return className.newInstance();
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param className
	 * @return
	 * @throws ClassNotFoundException 
	 */
	public static Class createClass(String className) throws ClassNotFoundException {
		try {
			ClassLoader classLoader=ClassUtil.class.getClassLoader();
			return classLoader.loadClass(className);
		} catch (ClassNotFoundException e1) {
			try{
				return Thread.currentThread().getContextClassLoader().loadClass(className);
			} catch (ClassNotFoundException e) {
				Debug.logError(e, "class does not exist," + className);
				throw new ClassNotFoundException("class does not exist", e);
			}
		}
	}
}
